import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import ArticleItem from '@/components/ArticleItem'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import {
  getArticleListByChannelId,
  getNewestArticleList,
} from '@/store/actions'

import styles from './index.module.scss'
import { RootState } from '@/types/store'

// 该文章的获取的id类型
type poros = {
  channelId: number
}

const ArticleList = ({ channelId }: poros) => {
  const dispatch = useDispatch()
  const history = useHistory()

  // 获取当前文章列表的数据
  const { channelsArticle } = useSelector((state: RootState) => state.home)

  // 此处的文章内容有可能为undefined 文章列表数据可能不存在  设置默认值
  // pre_timestamp 时间戳
  const cuentChannelsArticle = channelsArticle[channelId] ?? {
    pre_timestamp: Date.now() + '',
    results: [],
  }

  const { pre_timestamp, results } = cuentChannelsArticle

  // 是否还有更多内容  pre_timestamp 值为null  说明没有更多数据了
  // 此时 InfiniteScroll 组件的hasMore值为false,不会再加载数据了
  const hasMore = pre_timestamp !== null

  // 下拉加载数据 获得最新数据
  const onRefresh = async () => {
    
    await dispatch(getNewestArticleList(channelId, Date.now() + ''))
  }

  // 上拉加载更多内容
  const loadMore = async () => {
    await dispatch(getArticleListByChannelId(channelId, pre_timestamp))
  }
  return (
    <div className={styles.root}>
      {/* 文章列表中的每一项 */}
      <PullToRefresh onRefresh={onRefresh}>
        {results.map((item, index) => {
          const {
            art_id,
            title,
            aut_name,
            pubdate,
            comm_count,
            cover: { images, type },
          } = item
          const articleData = {
            title,
            aut_name,
            comm_count,
            pubdate,
            type,
            images,
          }
          return (
            <div
              className="article-item"
              key={index}
              onClick={() => history.push(`/articles/${art_id}`)}
            >
              <ArticleItem {...articleData} />
            </div>
          )
        })}

        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
